/*
 * Copyright 2009-2015 by WWW.KNET.CN  All rights reserved.
 */
package cn.knet.sp.ncrm.modules.call.config.web;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.knet.sp.ncrm.common.persistence.AjaxMessage;
import cn.knet.sp.ncrm.common.utils.DateUtils;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.web.BaseController;
import cn.knet.sp.ncrm.modules.call.config.entity.CallConfig;
import cn.knet.sp.ncrm.modules.call.config.entity.CallConfigType;
import cn.knet.sp.ncrm.modules.call.config.service.CallConfigService;

/**
 * 呼叫中心参数配置
 *
 * @author zhangbin
 * @version 2015 /07/07 17:18:10
 */
@Controller
@RequestMapping(value = "${adminPath}/call/config/callConfig")
public class CallConfigController extends BaseController {

	@Autowired
	private CallConfigService callConfigService;


	private String convertDate(String str) throws ParseException {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		Date date = DateUtils.parseDate(str, "HH:mm:ss");
		return DateUtils.formatDate(date, "HHmmss");
	}

	private void updateWorkShift(CallConfig callConfig, AjaxMessage result) {
		try {
			String workshift1s = convertDate(callConfig.getWorkShift1start());
			String workshift1e = convertDate(callConfig.getWorkShift1end());
			String workshift2s = convertDate(callConfig.getWorkShift2start());
			String workshift2e = convertDate(callConfig.getWorkShift2end());
			callConfigService.updateWorkShifts(workshift1s, workshift1e, workshift2s, workshift2e);
		} catch (ParseException e) {
			logger.warn("日期转换失败!", e);
			result.makeError("日期格式错误");
		}
	}

	/*private void updateRate(CallConfig callConfig, AjaxMessage result) {
		if (callConfig.getQuickRingSec() < 1) {
			result.makeError("快速接听时间不能小于一秒");
		} else {
			callConfigService.updateRate(callConfig.getQuickRingSec());
		}
	}*/

	private void updateCalling(CallConfig callConfig, AjaxMessage result) {
		if (callConfig.getLongCallSec() == null) {
			result.makeError("较长通话秒数不能为空");
		}
		if (callConfig.getTimeOutSec() == null) {
			result.makeError("超时接通秒数不能为空");
		}
		if (callConfig.getLongCallSec() == null) {
			result.makeError("快速接听秒数不能为空");
		}
		if (StringUtils.isBlank(callConfig.getWorkEndTime())) {
			result.makeError("最后统计时间不能为空");
		}
		if (!result.isSuccess()) {//有错则退出
			return;
		}

		if (callConfig.getLongCallSec() < 1 || callConfig.getTimeOutSec() < 1) {
			result.makeError("较长通话秒数和超时接通秒数不能小于1秒");
		} else {
			callConfigService.updateCalling(callConfig.getLongCallSec(), callConfig.getTimeOutSec());
		}
		if (callConfig.getQuickRingSec() < 1) {
			result.makeError("快速接听时间不能小于一秒");
		} else {
			callConfigService.updateRate(callConfig.getQuickRingSec());
		}
		if (StringUtils.isNotBlank(callConfig.getWorkEndTime())) {
			try {
				String workEndingTime = convertDate(callConfig.getWorkEndTime());
				callConfigService.updateWorkEndingTime(workEndingTime);
			} catch (ParseException e) {
				logger.warn("日期转换失败!", e);
				result.makeError("日期格式错误");
			}

		}

	}

	@RequiresPermissions("call:config:callConfig:view")
	@RequestMapping(value = {"/show", ""}, method = {RequestMethod.GET, RequestMethod.POST})
	public String list(Model model, CallConfig callConfig, HttpServletRequest request,
					   HttpServletResponse response) {
		//初始化信息
		callConfigService.initCallConfig(callConfig);
		model.addAttribute("config", callConfig);
		return "modules/call/config/callConfig";
	}


	@RequiresPermissions("call:config:callConfig:updateconfig")
	@RequestMapping(value = {"/update"}, method = {RequestMethod.POST})
	@ResponseBody
	public Object update(Model model, CallConfig callConfig, HttpServletRequest request,
						 HttpServletResponse response) {
		AjaxMessage result = AjaxMessage.success();
		CallConfigType callConfigType = callConfig.getCallConfigType();
		switch (callConfigType) {
			case WORKSHIFT:
				updateWorkShift(callConfig, result);
				if (result.isSuccess()) {
					result.setMessage("修改班次成功");
				}
				break;
			case CALLING:
				updateCalling(callConfig, result);
				if (result.isSuccess()) {
					result.setMessage("修改通话参数成功");
				}
				break;
			/*case RATE:
				updateRate(callConfig, result);
				if (result.isSuccess()) {
					result.setMessage("修改快速接听时间成功");
				}
				break;*/
			case EXECUTE:

				break;
			default:
				return AjaxMessage.error("不支持的类型");
		}
		return result;
	}


	@RequiresPermissions("call:config:callConfig:execute")
	@RequestMapping(value = {"/excute"}, method = {RequestMethod.POST})
	@ResponseBody
	public Object update(Model model, HttpServletRequest request,
						 HttpServletResponse response) {
		AjaxMessage result = AjaxMessage.success();
		try {
			callConfigService.executeStat();
		} catch (Exception e) {
			logger.error("执行统计存储过程报错,请检查日志!", e);
			result.makeError("执行失败!");
		}
		result.setMessage("重新执行统计成功");
		return result;
	}

	@RequiresPermissions("call:config:callConfig:group")
	@RequestMapping(value = {"/group"}, method = {RequestMethod.POST})
	@ResponseBody
	public Object updateGroup(Model model, @RequestParam(value = "groupList[]", required = false) String[] groupList,
							  CallConfigType type,
							  HttpServletRequest request,
							  HttpServletResponse response) {
		AjaxMessage result = AjaxMessage.success();
		try {
			if (CallConfigType.INGROUP.equals(type) || CallConfigType.OUTGROUP.equals(type)) {
				Set<String> set = new LinkedHashSet<String>();
				if (groupList != null) {
					for (String groupId : groupList) {
						set.add(groupId);
					}
				}
				callConfigService.updateGroups(set, type);
				result.setMessage("组织机构修改完毕");
			} else {
				result.makeError("参数错误!");
			}
		} catch (Exception e) {
			logger.error("修改组织机构失败,请检查日志!", e);
			result.makeError("执行失败!");
		}
		return result;
	}

}
